"""
题目四：新建“test4”Python文件：读取素材中的“test.txt”文件，使用jieba库进行分词，
并将出现次数前5的词汇和出现次数信息写入到“output.txt”文件中。（30分）
"""
import jieba


def duqu():  # 读取文件中的前五的词汇和出现的次数
    with open('test.txt', 'r', encoding='utf-8') as f:
        s = jieba.lcut(f.read())
        dict1 = {}
        list1 = []
        for i in s:
            if len(i) == 1:
                continue
            else:
                if dict1.get(i) is None:
                    dict1[i] = 1
                else:
                    dict1[i] += 1
        for i in dict1:
            j = dict1.get(i)
            list1.append((i, j))
        list1.sort(key=lambda x: list(x)[1], reverse=True)
        return list1


def xieru():  # 写入output.txt文件中
    list1 = duqu()
    with open('output.txt', 'w', encoding='utf-8')as f:
        for i in range(5):
            f.write(f'{list1[i][0]},{list1[i][1]}\n')


if __name__ == '__main__':
    xieru()
